package com.example.resultinterceptor.advice;


import com.alibaba.fastjson.JSONObject;

import com.gosun.uap.authnew.config.ResultAdviceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 结果拦截器 - 使用HandlerInterceptor实现
 * 为指定URL的返回消息添加前缀并处理错误信息
 *
 * @author luojiawei
 */
@RestControllerAdvice
public class ResultAdvice implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(ResultAdvice.class);

    private final ResultAdviceConfig config;
    public ResultAdvice(ResultAdviceConfig config) {
        this.config = config;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return config.isEnabled();
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        try {
            String requestUri = request.getURI().getPath();
            logger.debug("拦截器处理请求: {}", requestUri);
            // 检查是否应该拦截
            if (!config.shouldIntercept(requestUri)) return body;
            //如果是String或基础类型则直接返回
            if (body instanceof String) {
                logger.debug("非允许的类型的响应，直接返回: {}", body);
                if(config.containsJdbcError((String) body)){
                    return config.getInternalErrorMsg();
                }
                return body;
            }
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(body);
            // 遍历一层信息(可能不知道具体的错误信息在哪个字段中就遍历第一层字段)
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                if (value instanceof String message && config.containsJdbcError(message)) {
                    jsonObject.put(key, config.getInternalErrorMsg());
                    break;
                }
            }
            body = jsonObject.toJavaObject(Object.class);
            return body;
        } catch (Exception e) {
            logger.error("处理结果时发生异常: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
